const mongoose = require('mongoose');
const config = require('../src/config/config');
const Food = require('../src/models/food.model');

/**
 * 为foods集合中的所有文档添加isDeleted字段
 * 如果文档已经有isDeleted字段，则不做修改
 */
async function addIsDeletedToFoods() {
  try {
    // 连接到MongoDB
    console.log('正在连接到MongoDB...');
    await mongoose.connect(config.mongoose.url, config.mongoose.options);
    console.log('MongoDB连接成功');

    // 查找所有没有isDeleted字段的文档
    const result = await Food.updateMany(
      { isDeleted: { $exists: false } },
      { $set: { isDeleted: false } }
    );

    console.log(`已更新 ${result.modifiedCount} 个文档，添加了isDeleted字段`);
    console.log(`${result.matchedCount} 个文档被匹配，${result.modifiedCount} 个文档被修改`);

    // 关闭数据库连接
    await mongoose.disconnect();
    console.log('数据库连接已关闭');
    process.exit(0);
  } catch (error) {
    console.error('执行脚本时出错:', error);
    // 关闭数据库连接
    if (mongoose.connection.readyState !== 0) {
      await mongoose.disconnect();
      console.log('数据库连接已关闭');
    }
    process.exit(1);
  }
}

// 执行脚本
addIsDeletedToFoods();